using BaseData.Domain;
using BaseData.Infrastructure;
using Essensoft.Paylink.Alipay;
using Essensoft.Paylink.Alipay.Notify;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace BaseData.API.Read.Controllers
{
    /// <summary>
    /// 支付宝支付回调控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AlipayNotifyController : ControllerBase
    {
        private readonly ILogger<AlipayNotifyController> _logger;
        private readonly IAlipayNotifyClient _notifyClient;
        private readonly DataDbContext _dbContext;
        private readonly IOptions<AlipayOptions> _optionsAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AlipayNotifyController(
            ILogger<AlipayNotifyController> logger, 
            IAlipayNotifyClient notifyClient,
            DataDbContext dbContext,
            IOptions<AlipayOptions> optionsAccessor)
        {
            _logger = logger;
            _notifyClient = notifyClient;
            _dbContext = dbContext;
            _optionsAccessor = optionsAccessor;
        }

        /// <summary>
        /// 电脑网站支付异步通知
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> PagePay()
        {
            try
            {
                // 解析支付宝的异步通知
                var notify = await _notifyClient.ExecuteAsync<AlipayTradePagePayNotify>(Request, _optionsAccessor.Value);
                
                // 记录日志
                _logger.LogInformation($"收到支付宝异步通知，订单号：{notify.OutTradeNo}，交易号：{notify.TradeNo}，交易状态：{notify.TradeStatus}");

                // 验证通知的真实性
                if (notify != null)
                {
                    // 判断交易状态
                    if (notify.TradeStatus == "TRADE_SUCCESS" || notify.TradeStatus == "TRADE_FINISHED")
                    {
                        // 支付成功，向流水表添加记录
                        var amount = new Amount
                        {
                            OperatingNum = notify.OutTradeNo, // 商户订单号
                            Source = "支付宝支付", // 来源
                            PaymentMethod = "支付宝", // 支付方式
                            PaymentAmount = decimal.Parse(notify.TotalAmount), // 支付金额
                            PaymentStatus = true, // 支付状态：成功
                            Balance = 0, // 根据业务需求设置余额，这里默认为0
                            OperatingTime = DateTime.Now // 操作时间
                        };

                        // 检查是否已经存在该订单的流水记录（防止重复通知）
                        var existingAmount = _dbContext.Amounts.FirstOrDefault(a => a.OperatingNum == notify.OutTradeNo && a.PaymentStatus == true);
                        if (existingAmount == null)
                        {
                            // 添加流水记录
                            _dbContext.Amounts.Add(amount);
                            await _dbContext.SaveChangesAsync();

                            _logger.LogInformation($"订单 {notify.OutTradeNo} 支付成功，已添加流水记录，金额：{notify.TotalAmount}元");
                        }
                        else
                        {
                            _logger.LogWarning($"订单 {notify.OutTradeNo} 的流水记录已存在，跳过添加");
                        }

                        // 返回 success 给支付宝，表示已成功接收通知
                        return Content("success");
                    }
                    else
                    {
                        _logger.LogWarning($"订单 {notify.OutTradeNo} 交易状态异常：{notify.TradeStatus}");
                        return Content("success"); // 即使状态不是成功，也要返回success，避免支付宝重复通知
                    }
                }
                else
                {
                    _logger.LogError("支付宝异步通知解析失败或验签失败");
                    return Content("failure");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理支付宝异步通知时发生异常");
                return Content("failure");
            }
        }
    }
}

